<?php

namespace app\controller;

use app\BaseController;
use Exception;
use think\captcha\facade\Captcha;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Session;

class Auth extends BaseController
{
    /**
     * 用户登录接口
     * 通过username、password、captcha参数验证并返回token和refreshToken
     */
    public function login()
    {
        try {
            $data = input('post.');
            if (!isset($data['username']) || !isset($data['password']) || !isset($data['captcha'])) {
                return returnJson(1, '参数不完整');
            }
            if (!Captcha::check($data['captcha'])) return returnJson(900, '图形验证码错误');
            $decryptedHash = decryptPassword($data['password']);
            if (!$decryptedHash) return returnJson(5, '密码解密失败，请核对系统时间后重试');

            $user = Db::table('tb_user')->where(['username' => $data['username'], ['password', '=', hash('sha256', 'sckey_' . $decryptedHash)]])->field('id, username, status, type')->find();

            if (!$user) return returnJson(4, '用户名或密码错误');
            if ($user['status'] != 1) return returnJson(3, '用户已被禁用');

            $token = $this->generateToken($user['id']);
            $refreshToken = $this->generateToken($user['id']);

            Cache::set('token:' . $token, $user['id'], 3600);
            Cache::set('refresh:' . $refreshToken, $user['id'], 7 * 24 * 3600);
            // 记录登录日志
            $this->recordLoginLog($user['id']);
            Session::set('user', ['uid' => $user['id'], 'username' => $user['username'], 'type' => $user['type'] ?? 0]);
            return returnJson(data: ['token' => $token, 'refreshToken' => $refreshToken, 'expireTime' => 3600 // token有效期1小时
                ]);
        } catch (Exception $e) {
            return returnJson(2, '登陆失败' . $e->getMessage());
        }
    }

    /**
     * 生成token
     */
    private function generateToken($userId)
    {
        $random = bin2hex(random_bytes(16));
        $timestamp = time();
        return hash('sha256', $userId . $random . $timestamp);
    }


    /**
     * 记录登录日志
     */
    private function recordLoginLog($userId)
    {
        Db::table('tb_login_log')->insert(['uid' => $userId, 'ip' => request()->ip(), 'user_agent' => request()->server('HTTP_USER_AGENT'), 'login_time' => date('Y-m-d H:i:s')]);
    }

    /**
     * 发送验证码
     */
    public function sendCaptcha()
    {
        $data = input('post.');
        if (!empty($data['captcha']) and (!empty($data['phone']) or !empty($data['email']))) {
            return returnJson(1, '参数不完整');
        }

        // 验证图形验证码
        if (!Captcha::check($data['captcha'])) {
            return returnJson(900, '图形验证码错误');
        }

        // 检查手机号参数
        if (isset($data['phone']) && !empty($data['phone'])) {
            return returnJson(1, "暂时不支持发送短信");
        }

        //检查60秒内是否发送过验证码 若有返回剩余等待时间
        if (Cache::get($data['email'] . "time") and (time() - Cache::get($data['email'] . "time") < 60)) {
            return returnJson(101, msg: "请勿频繁发送", data: ["waitSeconds" => 60 - (time() - Cache::get($data['email'] . "time"))]);
        }

        $email = $data['email'];
        $code = rand(100000, 999999);
        $res = sendEmailCode($email, $code);

        if ($res) {
            Cache::set($email . "time", time(), 60);
            Cache::set($email . "code", $code, 300);
            Session::delete('captcha');
            return returnJson(msg: "发送成功", data: ['waitSeconds' => 60]);
        } else {
            return returnJson(3, msg: "发送失败");
        }
    }

    public function refreshCaptcha()
    {
        $data = input('post.');
        if (!empty($data['captcha']) and (!empty($data['phone']) or !empty($data['email']))) {
            return returnJson(1, '参数不完整');
        }
        // 验证图形验证码
        if (!Captcha::check($data['captcha']))
            return returnJson(900, '图形验证码错误');
        if (empty($data['email']))
            $value=$data['phone'];
         else
            $value=$data['email'];
        $code = $data['code'];

        if (Cache::get($value . "code") != $code)
            return returnJson(5, msg: "验证码错误");

        Cache::delete($value . "code");
        return returnJson(msg: "验证成功");
    }

    /**
     * 刷新token接口
     */
    public function refreshToken()
    {
        $data = input('post.');

        if (!isset($data['refreshToken'])) {
            return returnJson(1, '缺少refreshToken参数');
        }

        // 验证refreshToken
        $userId = Cache::get('refresh:' . $data['refreshToken']);

        if (!$userId) {
            return returnJson(2, '无效的refreshToken');
        }

        // 生成新的token
        $newToken = $this->generateToken($userId);

        if ($newToken != $data['refreshToken']) {}
        //$newRefreshToken = $this->generateToken($userId);

        Cache::set('token:' . $newToken, $userId, 3600);
        //Cache::set('refresh:' . $newRefreshToken, $userId, 7 * 24 * 3600);

        Cache::delete('refresh:' . $data['refreshToken']);

        return returnJson(data: ['token' => $newToken,  'expireTime' => 3600]);
    }



    /**
     * 登出接口
     */
    public function logout()
    {
        // 获取token
        $token = request()->header('Authorization');

        if ($token) {
            // 移除Bearer前缀
            $token = str_replace('Bearer ', '', $token);
            // 删除token
            Cache::delete('token:' . $token);
        }

        // 清除session
        Session::delete('user');

        return returnJson(msg: '登出成功');
    }

    /**
     * 获取用户信息接口
     */
    public function getUserInfo()
    {
        // 验证用户登录状态
        $user = checkLogin();

        // 获取用户详细信息
        $userInfo = Db::table('tb_user')->where('id', $user['uid'])->field('id, username')->find();

        // 构建返回数据
        $data = ['userId' => $userInfo['id'], 'userName' => $userInfo['username'], 'roles' => ['R_SUPER'], // 这里返回默认角色，实际项目中应该从数据库查询用户角色
            'buttons' => ['B_CODE1', 'B_CODE2', 'B_CODE3'] // 这里返回默认按钮权限，实际项目中应该从数据库查询用户权限
        ];

        return returnJson(code: 0, msg: '成功', data: $data);
    }
}